package com.example.fileprovider;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.usermodel.PictureType;

import java.io.*;
/**
 * project:
 * author: wzq
 * date: 2014/6/30
 * description: 保存图片,有2个参数 folder + 前缀名 最终图片保存在 folder/前缀+suggestName
 */
public class OfficePicMgr implements PicturesManager {

    private String cachePrefix;
    private String folder;
    public OfficePicMgr(String folder, String cachePrefix) {
        this.cachePrefix = cachePrefix;
        this.folder = folder;
    }

    public void savePicture(PicInfo info) {
        savePicture(info.getContent(), PictureType.JPEG, getPicInfoPrefix(info), 0, 0);
    }

    public String getPicSavePath(PicInfo info) {
        return folder + "/" + cachePrefix + "_" + getPicInfoPrefix(info);
    }

    private String getPicInfoPrefix(PicInfo info) {
        StringBuilder sb = new StringBuilder();
        sb.append("_");
        sb.append(info.getSheetName());
        sb.append("_");
        sb.append(info.getRowNum());
        sb.append("_");
        sb.append(info.getColNum());
        sb.append("_");
        sb.append(info.getPicName());
        return sb.toString();
    }

    @Override
    public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
                              float heightInches) {

        String name = cachePrefix + "_" + suggestedName;
        try {
            File file = new File(folder, name);
            LogMgr.d("save image to " + file.getAbsolutePath());
            File dir = file.getParentFile();
            if(!dir.exists()) {
                dir.mkdir();
            }
            OutputStream out = new FileOutputStream(file);
            if(content != null && content.length > 0) {
                out.write(content, 0, content.length);
            }
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        return name;
    }
}
